<template>
  <el-dialog :draggable="true" v-model="dialogVisible" :title="title" width="600px" :destroy-on-close="true"
    @close="handleClose">
    <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px">
      <el-form-item label="区域名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入区域名称" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { handleError } from '@/utils/handleError';
import { useCompanyStore } from '@/stores/company';

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  title: {
    type: String,
    required: true
  },
  formData: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['update:modelValue', 'submit', 'close', 'refresh'])

const formRef = ref(null)
const form = ref({
  id: null,
  name: '',
  ratio: 0.9
})

// 保存原始区域数据用于比对
const originalAreaData = ref(null)

const formRules = {
  name: [
    { required: true, message: '请输入区域名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

watch(() => props.formData, (newVal) => {
  form.value = {
    ...newVal,
    ratio: 0.9
  }

  // 保存原始区域数据
  originalAreaData.value = {
    name: newVal.name
  }
}, { deep: true })

let companyStore = useCompanyStore()

async function handleSubmit() {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          id: form.value.id,
          name: form.value.name,
          ratio: 0.9,
          company_id: companyStore.currentCompany.id
        }
        emit('submit', submitData)
        ElMessage.success('保存成功')
      } catch (error) {
        handleError(error, '保存失败', true)
      }
    }
  })
}

function handleClose() {
  formRef.value?.resetFields()
  emit('close')
}
</script>

<style scoped>
.el-divider {
  margin: 16px 0;
}

.ml-2 {
  margin-left: 8px;
}

:deep(.el-input-number) {
  width: 180px;
}
</style>